

package com.gc.server.service.impl;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.gc.server.dao.LinkGoodsDao;
import com.gc.server.dao.ShopDao;
import com.gc.server.entity.LinkGoodsEntity;
import com.gc.server.entity.ShopEntity;
import com.gc.server.vo.down.SaleSumDown;
import com.yf.response.RRException;
import org.springframework.transaction.annotation.Transactional;
import com.gc.server.vo.up.SaleRecordUp;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.excel.context.AnalysisContext;
import java.io.InputStream;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.stereotype.Service;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import  com.gc.server.vo.down.SaleRecordDown;

import java.util.*;
import java.io.IOException;
import java.net.URLEncoder;
import com.gc.server.vo.down.SaleRecordDown;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;
import com.gc.server.dao.SaleRecordDao;
import com.gc.server.entity.SaleRecordEntity;
import com.gc.server.vo.SaleRecordVo;
import com.gc.server.service.SaleRecordService;
import com.yf.service.impl.BaseServiceImpl;

/**
 * 账户记录Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date ${datetime}
 */
@Service
public class SaleRecordServiceImpl extends BaseServiceImpl<SaleRecordEntity> implements SaleRecordService {

    private SaleRecordDao dao;


    @Autowired
    public void setDao(SaleRecordDao dao) {
        this.dao = dao;
        super.setBaseDao(dao);
    }




    @Override
    public List<SaleRecordVo> findVo(SaleRecordVo vo){
        return dao.findVo(vo);
    }

    @Override
    public SaleRecordVo getVo(Long id){
        return dao.getVo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveVo(SaleRecordVo vo){
        ShopEntity shopEntity = shopDao.findByCode(vo.getShop().getCode());
        LinkGoodsEntity goodsEntity = linkGoodsDao.findByCode(vo.getGoods().getCode());
        if(shopEntity==null||goodsEntity==null){
            throw new RRException("数据不匹配");
        }
        vo.getEntity().setShopId(shopEntity.getId());
        vo.getEntity().setGoodsId(goodsEntity.getId());
        return dao.save(vo.getEntity());
    }

    @Autowired
    private ShopDao shopDao;

    @Autowired
    private LinkGoodsDao linkGoodsDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateVo(SaleRecordVo vo){
        return dao.update(vo.getEntity());
    }



    @Override
    public void downLoad(HttpServletResponse response, List<SaleRecordVo> list) {
        ExcelWriter excelWriter = null;
        try {
            List<SaleRecordDown> datas = list.stream().map(item -> new SaleRecordDown(item)).collect(Collectors.toList());
            response.setContentType("application/vnd.ms-excel" );
            response.setCharacterEncoding("utf-8" );
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8" );
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx" );
//            EasyExcel.write(response.getOutputStream(), SaleRecordDown.class).sheet("模板" ).doWrite(datas);
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            //第一个数据
            WriteSheet writeSheet = EasyExcel.writerSheet("记录").head(SaleRecordDown.class).build();
            excelWriter.write(datas,writeSheet);
            //第二个数据
            Map<String,SaleSumDown> sum = new HashMap<>();
            datas.forEach(data ->{
                SaleSumDown sumDown ;
                String key = data.getGoodsCode();
                if(sum.containsKey(key)){
                    sumDown = sum.get(key);
                }else {
                    sumDown = new SaleSumDown(data.getGoodsName(),data.getShopCode(),0,data.getGoodsSpec());
                }
                sumDown.setAmount(sumDown.getAmount()+data.getAmount());
                sum.put(key,sumDown);
            });
            List<SaleSumDown> sumDowns = sum.values().stream().collect(Collectors.toList());
            writeSheet = EasyExcel.writerSheet("统计").head(SaleSumDown.class).build();
            excelWriter.write(sumDowns,writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }

    }



    @Override
    public void upload(InputStream file) {
        EasyExcel.read(file, SaleRecordUp.class, new UploadDataListener()).sheet().doRead();
    }

    class UploadDataListener extends AnalysisEventListener<SaleRecordUp> {


        @Override
        @Transactional(rollbackFor = Exception.class)
        public void invoke(SaleRecordUp upVo, AnalysisContext analysisContext) {

            saveVo(upVo.toVo());
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        }

    }




    /**内部方法**/



    /**外部方法实现**/

    @Override
    public Map sumByMonth(Date startDate, Date endDate, Long shopId, Long userId,Long headId,String level) {
        List<SaleRecordVo> recordVos = dao.findByDate(null,startDate,endDate,shopId, userId, headId,level);
        //按月份分类
        Map<Integer,List<SaleRecordVo>> monthSum = new HashMap<>();
        recordVos.forEach(recordVo -> {
            List<SaleRecordVo> list;
            int key = recordVo.getRecord().getTime().getMonth();
            if(monthSum.containsKey(key)){
                list = monthSum.get(key);
            }else {
                list = new ArrayList<>();
            }
            list.add(recordVo);
            monthSum.put(key,list);
        });
        //按月份统计
        Map<Integer,List<SaleSumDown>> result = new HashMap();
        monthSum.forEach((k,v)->{
            result.put(k,sum(v));
        });
        return result;
    }

    @Override
    public Map sumByShop(Integer month, Long shopId, Long userId, Long headId,String level) {
        List<SaleRecordVo> recordVos = dao.findByDate(month,null,null,shopId, userId, headId,level);
        //按店铺统计
        Map<String,List<SaleRecordVo>> map = new HashMap<>();
        recordVos.forEach(saleRecordVo -> {
            List<SaleRecordVo> saleRecordVos;
            String key = saleRecordVo.getShop().getShopName();
            if(map.containsKey(key)){
                saleRecordVos = map.get(key);
            }else {
                saleRecordVos = new ArrayList<>();
            }
            saleRecordVos.add(saleRecordVo);
            map.put(key,saleRecordVos);
        });
        //统计总数
        Map<String,List<SaleSumDown>> sum  = new HashMap<>();
        map.forEach((key,data)->{
            sum.put(key,sum(data));
        });
        return sum;
    }

    List<SaleSumDown> sum(List<SaleRecordVo> datas){
        Map<String,SaleSumDown> sum = new HashMap<>();
        datas.forEach(data ->{
            SaleSumDown sumDown ;
            String key = data.getGoods().getCode();
            if(sum.containsKey(key)){
                sumDown = sum.get(key);
            }else {
                sumDown = new SaleSumDown(data.getGoods().getName(),data.getGoods().getCode(),0,data.getGoods().getSpec());
            }
            sumDown.setAmount(sumDown.getAmount()+data.getRecord().getAmount());
            sum.put(key,sumDown);
        });
        return sum.values().stream().collect(Collectors.toList());
    }

}
